package top.anonyeast.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import top.anonyeast.dao.AdmissionDao;
import top.anonyeast.pojo.Admission;
import top.anonyeast.service.AdmissionService;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

@Service("admissionService")
public class AdmissionServiceImpl implements AdmissionService {
    @Resource(name = "admissionDao")
    private AdmissionDao admissionDao;  //DAO层接口
    private static String pyPath;  //python爬虫代码路径
    private static final String operatingSystem;  //操作系统
    private static int queryCount = 0;  //初始化查询次数

    /*
     * 获取python爬虫文件路径，并根据当前操作系统对路径做一定的处理
     */
    static {
        //获取py文件路径
        URL url = AdmissionServiceImpl.class.getResource("admission_query.py");
        pyPath = url.getPath();
        //获取当前操作系统
        operatingSystem = System.getProperty("os.name").toLowerCase();
        //输出路径和系统信息
        System.out.println("pythonPath = " + pyPath);
        System.out.println("OS = " + operatingSystem);
        //如果是windows系统要去除python爬虫文件路径的第一个斜杠,linux系统则要去除file:前缀
        if (operatingSystem.contains("windows")) {
            pyPath = pyPath.replaceFirst("/", "");
        } else {
            pyPath = "/www/wwwroot/luqu.anonyeast.top/admission_query.py";
        }
    }

    /**
     * 查询录取信息
     * @param candidateNumber 考生号
     * @param studentName 姓名
     * @param searchType 考生号类型
     * @return 录取信息
     */
    @Override
    public Admission findAll(String candidateNumber, String studentName, int searchType) {
        //定义执行python爬虫代码需要的参数
        String[] args = {"python", pyPath, candidateNumber, studentName, String.valueOf(searchType)};
        //如果是linux系统，python程序需要指定完整路径
        if (operatingSystem.contains("linux")){
            args[0] = "/usr/local/miniconda3/bin/python";
        }
        //输出完整命令用于查看
        for (String arg : args) {
            System.out.print(arg + " ");
        }
        //定义录取信息的json字符串
        StringBuilder result_json = new StringBuilder();
        //开始通过java调用python爬虫脚本
        try {
            //执行python程序并传入参数
            Process process = Runtime.getRuntime().exec(args);
            //获取字符缓冲输入流
            BufferedReader bfr;
            //Windows系统要使用gbk编码，其他系统用utf-8
            if (operatingSystem.contains("windows")) {
                bfr = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
            } else {
                bfr = new BufferedReader(new InputStreamReader(process.getInputStream()));
            }
            //读取python程序的输出信息
            String line = null;
            while ((line = bfr.readLine()) != null) {
                result_json.append(line);
            }
            bfr.close();
            process.waitFor();

            //解析python输出的录取信息为Admission对象
            ObjectMapper om = new ObjectMapper();
            Admission admission = om.readValue(result_json.toString().trim(), Admission.class);
            //输出Admission对象并返回
            System.out.println(admission);
            return admission;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加录取信息到数据库
     * @param admission 录取信息
     * @return
     */
    @Override
    public int addToDB(Admission admission) {
        QueryWrapper<Admission> wrapper = new QueryWrapper<>();
        wrapper.eq("id_card", admission.getId_card());
        //先查询数据库是否已经存在这条记录，不存在才插入
        Integer count = admissionDao.selectCount(wrapper);
        if (count > 0) {
            return 0;
        } else {
            return admissionDao.insert(admission);
        }
    }

    /**
     * 查询完成后增加查询次数
     */
    @Override
    public void queryCount() {
        queryCount++;
    }

    /**
     * 获取查询次数
     * @return
     */
    @Override
    public int getQueryCount() {
        return queryCount;
    }
}
